package cn.tedu.store.web;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DownloadServlet
 */
public class DownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, 
			HttpServletResponse response) 
					throws ServletException, IOException {
		byte[] bytes=createPng("World!");
		response.setContentType("image/png");
		response.setContentLength(bytes.length);
		String name="演示图片.png";
		//中文必须进行URL编码处理
		name=URLEncoder.encode(name,"UTF-8");
		response.setHeader("Content-Disposition", 
				"attachment; filename=\""+name+"\"");
		//填充Body
		OutputStream out=response.getOutputStream();
		out.write(bytes);
		out.flush();
		out.close();
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}
	
	
	private byte[] createPng(String code) throws IOException{
		//创建图片对象
		BufferedImage img=new BufferedImage(100, 40, BufferedImage.TYPE_3BYTE_BGR);
		//img.setRGB(0, 0, 0x0000ff);
		//img.setRGB(50, 20,0xffff00);
		Random r=new Random();
		for(int i=0;i<500;i++) {
			int x=r.nextInt(img.getWidth());
			int y=r.nextInt(img.getHeight());
			int rgb=r.nextInt(0xFFFFFF);
			img.setRGB(x, y, rgb);
		}
		Graphics2D g=img.createGraphics();
		Color c=new Color(r.nextInt(0xFFFFFF));
		g.setColor(c);
		//黑体，斜体，字体的大小
		Font font=new Font(Font.SANS_SERIF,Font.ITALIC,35);
		g.setFont(font);
		g.drawString(code, 5, 36);
		//利用API绘制混淆线
		for(int i=0;i<5;i++) {
			int x1=r.nextInt(img.getWidth());
			int y1=r.nextInt(img.getHeight());
			int x2=r.nextInt(img.getWidth());
			int y2=r.nextInt(img.getHeight());
			g.drawLine(x1, y1, x2, y2);
		}
		//将图片对象编码为png数据
		ByteArrayOutputStream out=new ByteArrayOutputStream();
		ImageIO.write(img, "png", out);
		out.close();
		byte[] bytes=out.toByteArray();
		return bytes;
	}

}
